package com.sky.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeEditPasswordDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.time.LocalDateTime;
import java.util.List;

@Service

public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Value("${sky.md5.salt}")
    private  String salt;
    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus().equals(StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    @Override
    public void editPassword(EmployeeEditPasswordDTO employeeEditPasswordDTO) {
        Long id = employeeEditPasswordDTO.getEmpId();
        String password = employeeEditPasswordDTO.getNewPassword();//新密码
        String oldPassword = employeeEditPasswordDTO.getOldPassword();//旧密码

        Employee selectid = employeeMapper.selectid(id);//查询到数据里面的数据
        oldPassword = DigestUtils.md5DigestAsHex((oldPassword + salt).getBytes());
        password = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (selectid.getStatus().equals(StatusConstant.DISABLE) ) {//
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }
        if (!oldPassword.equals(selectid.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }
        if (oldPassword.equals(selectid.getPassword())) {
            selectid.setPassword(password);
        }
        employeeMapper.update(selectid);

    }

    @Override
    public void save(EmployeeDTO employeeDTO) {
        //创建实体类对象
        Employee employee = new Employee();
        //将employeeDTO的成员属性拷贝给employee
        BeanUtils.copyProperties(employeeDTO,employee);
        //创建时间与修改时间
        //employee.setCreateTime(LocalDateTime.now());
        //mployee.setUpdateTime(LocalDateTime.now());
        //设置默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex((PasswordConstant.DEFAULT_PASSWORD+salt).getBytes()));
        //设置默认状态
        employee.setStatus(StatusConstant.ENABLE);
        //设置创建人和修改人
        //employee.setCreateUser(BaseContext.getCurrentId());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.save(employee);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public Employee selectid(Long id) {
        //传递要查询id
         Employee employee= employeeMapper.selectid(id);
        return employee;
    }
    /**
     * 员工启用禁用接口
     * @param status
     * @param id
     */
    @Override
    public void updete(Integer status, Long id) {
        //获得修改人的id
        Long currentId = BaseContext.getCurrentId();
        //链式编程
        Employee employee= Employee.builder()
                .id(id)
                .status(status)
                .updateTime(LocalDateTime.now())
                .updateUser(currentId)
                .build();
                employeeMapper.update(employee);


    }

    /**
     * 修改员工接口
     * @param employeeDTO
     */
    @Override
    public void upde(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //Long currentId = BaseContext.getCurrentId();
        BeanUtils.copyProperties(employeeDTO,employee);
       //employee.setUpdateTime(LocalDateTime.now());
       // employee.setUpdateUser(currentId);
        employeeMapper.update(employee);
    }

    /**
     * 分页查询
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult poge(EmployeePageQueryDTO employeePageQueryDTO) {
        //使用插件 设置参数
        PageHelper.startPage(employeePageQueryDTO.getPage(),employeePageQueryDTO.getPageSize());
        //得到查询的返回的数据列表
       /* List<Employee> page = employeeMapper.page(employeePageQueryDTO.getName());
        Page<Employee> pageQuery= (Page<Employee>) page;*/
         Page<Employee> pageQuery= employeeMapper.page(employeePageQueryDTO.getName());
         //封装数据返回
        long total = pageQuery.getTotal();//总条数
        List<Employee> result = pageQuery.getResult();//当前数据集合
        return new PageResult(total,result);//封装返回
    }
}
